import 'dart:async';
import 'package:canteen/edit_c_v.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:flutter/material.dart';
import 'package:canteen/menu_c_v.dart';
import 'package:canteen/component/dish_widget.dart';
import 'package:canteen/component/animation_ball_widget.dart';
import 'package:vibration/vibration.dart';

class EditSetMealPage extends StatefulWidget {
  const EditSetMealPage({super.key});

  static String id = 'edit_set_meal_page';

  @override
  State<EditSetMealPage> createState() => _EditSetMealPageState();
}

class _EditSetMealPageState extends State<EditSetMealPage> {
  String searchQuery = '';
  List<String> dishes = [];
  Map<String, int> totalNum = {};
  int dishNum = 0;
  bool openBS = false;
  final int animationTime = 200;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dishes = allDishes.map((e) => e.name).toList();
    getDishesNum();
  }

  void save() {
    setMeal.dishes = totalNum
        .map((key, value) => MapEntry(findDishByName(key, allDishes)!, value));
    Navigator.pop(context);
  }

  // void deleteDish(index) {
  //   setMeal.dishes.remove(findDishByName(
  //       totalNum.keys.toList()[index], setMeal.dishes.keys.toList()));
  //   totalNum.remove(totalNum.keys.toList()[index]);
  //   calcDishNum();
  // }

  void clearDishes() {
    setState(() {
      totalNum.clear();
      calcDishNum();
      openBS = false;
    });
  }

  void getDishesNum() {
    totalNum = setMeal.dishes.map((key, value) => MapEntry(key.name, value));
    calcDishNum();
  }

  void triggerVibration() async {
    // 检查设备是否支持震动
    bool canVibrate = await Vibration.hasVibrator() ?? false;
    if (canVibrate) {
      // 触发一次短震动
      Vibration.vibrate(duration: 100);
    }
  }

  void addDish(dishName, clickPosition) {
    setState(() {
      totalNum[dishName] =
          totalNum.containsKey(dishName) ? totalNum[dishName]! + 1 : 1;

      final RenderBox dishBox = context.findRenderObject() as RenderBox;
      final Offset dishCenter = dishBox.localToGlobal(Offset(
        clickPosition!.dx,
        clickPosition!.dy,
      ));

      final RenderBox bottomBox =
          context.findAncestorRenderObjectOfType<RenderBox>()!;
      final Offset bottomCenter = bottomBox.localToGlobal(Offset(
        70,
        bottomBox.size.height,
      ));

      // 添加动画小球
      final OverlayEntry entry = OverlayEntry(
        builder: (context) => AnimationBallWidget(
          animationTime: animationTime,
          startOffset: dishCenter,
          endOffset: bottomCenter,
        ),
      );
      Overlay.of(context).insert(entry);
      Timer(Duration(milliseconds: animationTime), () {
        setState(() {
          calcDishNum();
          entry.remove();
        });
      });
    });
  }

  void calcDishNum() {
    if (totalNum.isEmpty) {
      dishNum = 0;
      return;
    }
    dishNum =
        totalNum.values.toList().reduce((value, element) => value + element);
    totalNum.removeWhere((key, value) => value == 0);
  }

  List<String> getFilteredDishes() {
    if (searchQuery.isEmpty) {
      return dishes;
    }
    return dishes
        .where((dish) => dish.toLowerCase().contains(searchQuery.toLowerCase()))
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffbfbfb),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          '菜品',
          style: TextStyle(
              color: Colors.black, fontSize: 16),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
      ),
      body: Container(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              padding: EdgeInsets.symmetric(horizontal: 15),
              height: 46,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                border: Border.all(color: Colors.black),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.search_rounded,
                  ),
                  Expanded(
                    child: TextField(
                      onChanged: (value) {
                        setState(() {
                          searchQuery = value;
                        });
                      },
                      decoration: InputDecoration(
                        hintText: '搜索菜品',
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListView.builder(
                  itemCount: getFilteredDishes().length,
                  itemBuilder: (context, index) {
                    return DishWidget(
                      dishName: getFilteredDishes()[index],
                      childWidget: Row(
                        children: [
                          GestureDetector(
                            onTap: () {
                              if (totalNum[getFilteredDishes()[index]] ==
                                  0) {
                                return;
                              }
                              if (totalNum[getFilteredDishes()[index]] !=
                                  null) {
                                setState(() {
                                  totalNum[getFilteredDishes()[index]] =
                                      totalNum[
                                              getFilteredDishes()[index]]! -
                                          1;
                                });
                              }
                              calcDishNum();
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: Color(0xffc80815).withOpacity(0.2),
                                shape: BoxShape.circle,
                              ),
                              child: Icon(Icons.remove,
                                  color: Color(0xffc80815)),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 6),
                            padding: EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(
                                  color: Colors.black.withOpacity(0.2),
                                  width: 0.5),
                            ),
                            child: Text(
                              '${totalNum[getFilteredDishes()[index]] ?? 0}',
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 15),
                            ),
                          ),
                          GestureDetector(
                            onTapUp: (details) {
                              addDish(getFilteredDishes()[index],
                                  details.globalPosition);
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: Color(0xffc80815),
                                shape: BoxShape.circle,
                              ),
                              child: Icon(
                                Icons.add,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  }),
            ),
            Column(
              children: [
                AnimatedSwitcher(
                  duration: Duration(milliseconds: 150),
                  transitionBuilder:
                      (Widget child, Animation<double> animation) {
                    return SizeTransition(
                      child: child,
                      sizeFactor: animation,
                    );
                  },
                  child: Container(
                    key: ValueKey<bool>(openBS && dishNum != 0),
                    height: openBS && dishNum != 0 ? 300 : 0,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(25),
                        topLeft: Radius.circular(25),
                      ),
                    ),
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.symmetric(
                              vertical: 8.0, horizontal: 20),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '品名',
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Color(0xff1b1b1b),
                                    fontWeight: FontWeight.bold),
                              ),
                              Text(
                                '数量',
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Color(0xff1b1b1b),
                                    fontWeight: FontWeight.bold),
                              )
                            ],
                          ),
                        ),
                        Expanded(
                          child: ListView.builder(
                              itemCount: totalNum.length,
                              itemBuilder: (context, index) {
                                return DishWidget(
                                  dishName: totalNum.keys.toList()[index],
                                  childWidget: Row(
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          if (totalNum[totalNum.keys
                                              .toList()[index]] ==
                                              0) {
                                            return;
                                          }
                                          setState(() {
                                            totalNum[totalNum.keys
                                                .toList()[index]] = totalNum[
                                            totalNum.keys
                                                .toList()[index]]! -
                                                1;
                                          });
                                          calcDishNum();
                                        },
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color: Color(0xffc80815)
                                                .withOpacity(0.2),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(Icons.remove,
                                              color: Color(0xffc80815)),
                                        ),
                                      ),
                                      Container(
                                        margin: EdgeInsets.symmetric(
                                            horizontal: 6),
                                        padding: EdgeInsets.all(5),
                                        decoration: BoxDecoration(
                                          borderRadius:
                                          BorderRadius.circular(8),
                                          border: Border.all(
                                              color: Colors.black
                                                  .withOpacity(0.2),
                                              width: 0.5),
                                        ),
                                        child: Text(
                                          '${totalNum.values.toList()[index]}',
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 15),
                                        ),
                                      ),
                                      GestureDetector(
                                        onTapUp: (details) {
                                          addDish(getFilteredDishes()[index],
                                              details.globalPosition);
                                        },
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color: Color(0xffc80815),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(
                                            Icons.add,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }),
                        ),
                        GestureDetector(
                          onTap: () {
                            clearDishes();
                          },
                          child: Padding(
                            padding: const EdgeInsets.only(top: 12.0),
                            child: Text(
                              '清空',
                              style: TextStyle(
                                  color: Color(0xff1b1b1b),
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      if (dishNum > 0) {
                        openBS = !openBS;
                      }
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    height: 70,
                    decoration: BoxDecoration(
                      color: Colors.white,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.cloud_queue_rounded,
                              size: 42,
                              color: Color(0xff1b1b1b),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Text(
                              '$dishNum个',
                              style: TextStyle(
                                  fontSize: 24, color: Color(0xff1b1b1b)),
                            ),
                          ],
                        ),
                        GestureDetector(
                          onTap: () {
                            save();
                          },
                          child: AnimatedSwitcher(
                            duration: Duration(milliseconds: 200),
                            child: Container(
                              key: ValueKey<bool>(dishNum != 0),
                              alignment: Alignment.center,
                              width: 100,
                              height: 45,
                              decoration: BoxDecoration(
                                color: Color(0xffc80815),
                                borderRadius: BorderRadius.circular(25),
                              ),
                              child: Text(
                                '保存',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
